package com.acmen.easyapi.dbcp;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @Author acmen
 * @date2020-06-08
 */
@Component("jdbcService")
public class JdbcService {
    @Resource
    private JdbcTemplate jdbcTemplate;

    private static final Logger log = LoggerFactory.getLogger(JdbcService.class);

    /**
     * @param sql
     * @param args
     * @return
     */
    public int update(String sql,Object[] args) {
        return jdbcTemplate.update(sql, args);
    }

    public int[] batchUpdate(String sql, List<Object[]> batchArgs) {
        log.debug("Update SQL:{},参数:{}",sql,batchArgs);
        return jdbcTemplate.batchUpdate(sql, batchArgs);
    }

    public Long count(String sql,Object[] args){
        Map<String,Object> rowMap = jdbcTemplate.queryForMap(sql,args);
        for(Map.Entry<String,Object> entry : rowMap.entrySet()){
            log.debug("查询SQL:{},参数:{},返回count：{}",sql,args,entry.getValue());
            return (Long)entry.getValue();
        }
        log.debug("查询SQL:{},参数:{},返回count：{}",sql,args,0);
        return 0L;
    }


    /**
     * 只查找一条记录
     * @param sql
     * @param args
     * @return
     */
    public Map selectOne(String sql, Object[] args){
        List<Map> list = selectList(sql,args);
        if(list.isEmpty()){
            return null;
        }else{
            if(list.size()>1){
                log.warn("不只一条记录："+sql+"参数"+ JSON.toJSONString(args));
            }
            return list.get(0);
        }
    }

    public <T> T selectOne(String sql, Object[] args,Class<T> class1){
        List<T> list = selectList(sql,args,class1);
        if(list.isEmpty()){
            return null;
        }else{
            if(list.size()>1){
                log.warn("不只一条记录："+sql+"参数"+ JSON.toJSONString(args));
            }
            return list.get(0);
        }
    }

    public List selectList(String sql, Object[] args) {
        List dataList =  jdbcTemplate.queryForList(sql,args);
        log.debug("查询SQL:{},参数:{},返回记录数:{}",sql,args,dataList.size());
        return dataList;
    }

    public <T> List<T> selectList(String sql, Object[] args,Class<T> class1) {
        List<T> dataList = jdbcTemplate.query(sql,args, JavaObjectRowMapper.getInstance(class1));
        log.debug("查询SQL:{},参数:{},返回记录数:{}",sql,args,dataList.size());
        return dataList;
    }

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public JdbcService setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        return this;
    }
}
